package com.hebeiwangxiaozhang.product.service;

import com.hebeiwangxiaozhang.pojo.CommodityEsBody;
import com.hebeiwangxiaozhang.product.pojo.AttrsResults;
import com.hebeiwangxiaozhang.product.pojo.BrandResult;
import com.hebeiwangxiaozhang.product.pojo.ProductSearchBody;
import com.hebeiwangxiaozhang.product.pojo.ProductSearchResults;
import com.hebeiwangxiaozhang.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.xcontent.XContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ProductService {

    Logger logger= LoggerFactory.getLogger(ProductService.class);

    @Autowired
    private RestHighLevelClient highLevelClient;

    public List<String> onSaleToEs(List<CommodityEsBody> esBodies) {
        BulkRequest request = new BulkRequest();
        esBodies.forEach(body ->
            request.add(new IndexRequest().index("commodity").
                    id(body.getSkuId().toString()) //这样做的好处是，如果ES已经存在这个sku数据，则进行更新，不存在就新增，避免重复上架
                    .source(JsonUtils.toJSONString(body), XContentType.JSON)
            )
        );
        BulkResponse bulk = null;
        try {
            bulk = highLevelClient.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            logger.info("bulkrequest for product on-sale has exceptions, details error = {}", e);
        }
        List<String> failedBulkList = new ArrayList<>();
        if (bulk.hasFailures()) {
            for (BulkItemResponse res : bulk.getItems()) {
                if(res.isFailed()) {
                    failedBulkList.add(res.getId());
                }
            }
        }
        return failedBulkList;
    }

    public ProductSearchResults search(ProductSearchBody productSearchBody) {
        ProductSearchResults results = new ProductSearchResults();
        SearchRequest searchRequest = productSearchBody.generateSearchRequest();
        try {
            SearchResponse searchResponse = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //直接使用 searchResponse 前端就和你干起来了，所以我们需要再后端代码逻辑中进行结果的转化。
            /**
             * convert searchResponse to ProductSearchResults start
             *     private List<CommodityEsBody> products;
             *     private List<BrandResult> brands;
             *     private List<AttrsResults> attrs;
             *     private Integer pageNum;
             *     private Long totalProducts;
             */
            //private List<CommodityEsBody> products;
            SearchHits hits = searchResponse.getHits();
            if(hits.getHits() != null && hits.getHits().length > 0) {
                List<CommodityEsBody> products = new ArrayList<>();
                hits.forEach(hit -> products.add(
                        JsonUtils.readValue(hit.getSourceAsString(), CommodityEsBody.class)
                ));
                results.setProducts(products);
            }
            //private Integer pageNum; + private Long totalProducts;
            results.setPageNum(productSearchBody.getPageNum());
            results.setTotalProducts(hits.getTotalHits().value);

            //private List<BrandResult> brands;
            Aggregations aggregations = searchResponse.getAggregations();
            List<BrandResult> brands = new ArrayList<>();
            ParsedLongTerms brandAgg = aggregations.get("brandAgg");
            List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
            for (Terms.Bucket bucket : buckets) {
                long brandId = bucket.getKeyAsNumber().longValue();
                ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
                String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
                brands.add(new BrandResult(brandId, brandName));
            }
            results.setBrands(brands);

            //private List<AttrsResults> attrs;
            List<AttrsResults> attrsList = new ArrayList<>();
            ParsedNested attrs = aggregations.get("attrs");
            ParsedLongTerms attrIdAgg = attrs.getAggregations().get("attrIdAgg");
            List<? extends Terms.Bucket> attrsBuckets = attrIdAgg.getBuckets();
            attrsBuckets.forEach(bucket -> {
                long attrId = bucket.getKeyAsNumber().longValue();
                ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attrNameAgg");
                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();

                ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attrValueAgg");
                List<String> values = new ArrayList<>();
                for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                    values.add(attrValueAggBucket.getKeyAsString());
                }
                attrsList.add(new AttrsResults(attrId, attrName, values));
            });
            results.setAttrs(attrsList);
            /**
             * convert searchResponse to ProductSearchResults end
             */
            return results;
        } catch (Exception e) {
            throw new UnsupportedOperationException("");
        }
    }
}
